import model.SearchProductCondition
import util.IdGenerator
import util.DateUtils
import grails.converters.JSON
import java.text.SimpleDateFormat

class ImportProductController {

    def idGenerator = new IdGenerator()
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        if(!params.max) params.max = 10
        if(!params.offset) params.offset = 0
        if(!params.sort) params.sort = "id"
        if(!params.order) params.order = "desc"
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ importProductInstanceList: ImportProduct.list( params ), importProductInstanceTotal: ImportProduct.count() ]
    }

    def listSearch = {
        // 搜索日期不为空的情况
        if (params.searchDate_value ){
            def year = params.searchDate_year
            def month = params.searchDate_month
            def day = params.searchDate_day
            def searchDateStr = year + "-" + month + "-" + day
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd")
            Date searchDate = sdf.parse(searchDateStr)

            def criteria = ImportProduct.createCriteria()
            def resultList = criteria.list(params){
                ge("time",searchDate)
                le("time",searchDate+1)
            }
            render(view:"listSearch" , model:[importProductInstanceList:resultList])
        }
        // 搜索日期为空的情况
        else
            redirect(action:'list')
    }

    def show = {
        def importProductInstance = ImportProduct.get( params.id )

        if(!importProductInstance) {
            flash.message = "ImportProduct not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ importProductInstance : importProductInstance ] }
    }

    def delete = {
        def importProductInstance = ImportProduct.get( params.id )
        if(importProductInstance) {
            try {
                importProductInstance.delete()
                flash.message = "ImportProduct ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "ImportProduct ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "ImportProduct not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def importProductInstance = ImportProduct.get( params.id )

        if(!importProductInstance) {
            flash.message = "ImportProduct not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ importProductInstance : importProductInstance ]
        }
    }

    def update = {
        def importProductInstance = ImportProduct.get( params.id )
        if(importProductInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(importProductInstance.version > version) {
                    
                    importProductInstance.errors.rejectValue("version", "importProduct.optimistic.locking.failure", "Another user has updated this ImportProduct while you were editing.")
                    render(view:'edit',model:[importProductInstance:importProductInstance])
                    return
                }
            }
            importProductInstance.properties = params
            if(!importProductInstance.hasErrors() && importProductInstance.save()) {
                flash.message = "ImportProduct ${params.id} updated"
                redirect(action:show,id:importProductInstance.id)
            }
            else {
                render(view:'edit',model:[importProductInstance:importProductInstance])
            }
        }
        else {
            flash.message = "ImportProduct not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def importProductInstance = new ImportProduct()
        importProductInstance.properties = params
        return ['importProductInstance':importProductInstance]
    }

    def save = {
        def number = "进货号"+idGenerator.getId()
        def importProductInstance = new ImportProduct(params)
        if(!importProductInstance.hasErrors() && importProductInstance.save()) {
            importProductInstance.setNumber(number)
            flash.message = "ImportProduct ${importProductInstance.id} created"
            redirect(action:show,id:importProductInstance.id)
        }
        else {
            render(view:'create',model:[importProductInstance:importProductInstance])
        }
    }

    //产品查询的Action
    def search = { SearchProductCondition  searchCondition ->
    	if(request.method == "POST") {
            if(!params.sort) params.sort = "id"
            if(!params.order) params.order = "desc"

    		def criteria = ImportProduct.createCriteria()

    		def resultList = criteria.list(params){
    			and {
    				if(searchCondition.productName)
                    like ('productName',"%${searchCondition.productName}%")
				    if(searchCondition.modelNo)
                    like ('modelNo',"%${searchCondition.modelNo}%")
    			}
    		}
    		render(view:"listProduct" , model:[productList: resultList]);
    	}
    }

    //每批货物中每个产品销售的详细情况
    def productDetailList ={
        //if(!params.max) params.max = 10
        if(!params.sort) params.sort = "id"
        if(!params.order) params.order = "desc"

        ProductDTO dto = new ProductDTO()

        // 计算某批次货物库存
        def remain=null
        def hql1="select p.amount,p.inPrice,p.outPrice,p.modelNo,p.productName,p.supplier.supplierName,p.catalog.catalogName from ImportProduct p where p.number="+"'"+params.id+"'";
        def resultList1 = ImportProduct.executeQuery(hql1)

        def hql2="select sum(p.amount) from ExportProduct p where p.number="+"'"+params.id+"'";
        def resultList2 = ExportProduct.executeQuery(hql2)
        if (resultList2!=[null]){
            remain = resultList1[0][0]-resultList2[0]
        }
        else{
            remain = resultList1[0][0]
        }
        dto.setInPrice(resultList1[0][1])
        dto.setOutPrice(resultList1[0][2])
        dto.setModelNo(resultList1[0][3])
        dto.setProductName(resultList1[0][4])
        dto.setSupplierName(resultList1[0][5])
        dto.setCatalogName(resultList1[0][6])

        [ productInstanceList: ExportProduct.findAllByNumber(params.id),remain:remain,dto:dto ]
    }

    //产品批次销售情况
    def sellProduct = {
        def hql = "select a.number,a.amount,(a.amount-sum(b.amount)) as remain from ImportProduct a,ExportProduct b where a.number=b.number group by a.number"
        def resultList = Product.executeQuery(hql)
        def dataList = []
        resultList.each { s->
            def bar = ['number':s[0], 'amount':s[1],'remain':s[2]]
            dataList << bar
        }
        [sellProductList: dataList]
    }

    // 当前库存
    def listOnTime = {

        def hql = "select a.number from ImportProduct a where a.number not in (select b.number from ExportProduct b where b.hasSellOut = true) order by a.number desc"
        def resultList = Product.executeQuery(hql)

        // 当前库存为空的情况
        if (resultList == [])
        {
            render(view:"listOnTimeError")
        }
        // 当前库存不为空的情况
        else {

            def dataList = ImportProduct.findAll("from ImportProduct as p where p.number in (:numbers) order by p.id desc", [numbers:resultList])

            int totalSize = dataList.size()
            if (!params.max) {
                params.max = 10
            }
            if (!params.offset) {
                params.offset = 0
            }
            int start = params.offset.toInteger()
            int end = params.offset.toInteger() + params.max.toInteger() - 1
            if (end > totalSize) {
                end = totalSize - 1
            }
            if (end > 0) {
                IntRange ir = new IntRange(start, end)
                dataList= dataList.getAt(ir)
            }
            [importProductInstanceList: dataList,importProductInstanceTotal:totalSize]
        }
    }

}

